package day02;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;

import java.util.Date;

/**
 * @author chenshijie
 * @date 2023/12/15 14:51
 */

public class NettyClient {
    static int time = 0;
    public static void main(String[] args) throws InterruptedException {
        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup group = new NioEventLoopGroup();

        bootstrap
                // 1. 指定线程模型
                .group(group)
                // 2. 指定IO类型为NIO
                .channel(NioSocketChannel.class)
                // 3. IO处理逻辑
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder());

                    }
                });

        try {

            Channel channel = connect(bootstrap, "127.0.0.1", 8001, time);
            Thread.sleep(1000);

            while (true) {
                System.out.println(1);
                channel.writeAndFlush(new Date() + ": hello world!");
                Thread.sleep(2000);
            }
        } catch (Exception e) {
            System.out.println(1);
            e.printStackTrace();
            System.out.println("异常为" + e.getMessage());
        }

    }

    private static Channel connect(Bootstrap bootstrap, String host, int port, int time) throws Exception{
        GenericFutureListener<Future<? super Void>> futureListener = new GenericFutureListener<Future<? super Void>>() {
            @Override
            public void operationComplete(Future<? super Void> future) throws Exception {
                if (future.isSuccess()) {
                    System.out.println("连接成功！");
                } else {
                    System.out.println("第" + time + "次连接失败！开始重连");
                    // 重连
                    connect(bootstrap, host, port, time + 1);
                }
            }
        };
        System.out.println(futureListener);
        if (time >= 5) {
            System.out.println("失败次数过多，终止连接");
            throw new Exception("请检查网络连接！");
        }

        Channel channel = bootstrap
                .connect(host, port)
                .addListener(futureListener)
                .channel();
        return channel;
    }
}
